package com.lsk.gateway.Predicate;

import jakarta.validation.constraints.NotEmpty;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.HeaderRoutePredicateFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

@Component
public class UserRoutePredicateFactory extends AbstractRoutePredicateFactory<UserRoutePredicateFactory.Config> {


    public List<String> shortcutFieldOrder() {
        return Arrays.asList("role", "val");
    }

    public UserRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
      return new Predicate<ServerWebExchange>() {
          @Override
          public boolean test(ServerWebExchange exchange) {
              ServerHttpRequest request =exchange.getRequest();
              String first = request.getQueryParams().getFirst(config.getRole());
              return StringUtils.hasText(first) && first.equals(config.getVal());
          }
      };
    }

    @Validated
    public static class Config {
        private @NotEmpty String role;
        private String val;

        public String getRole() {
            return this.role;
        }


        public String getVal() {
            return this.val;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public void setVal(String val) {
            this.val = val;
        }
    }
}
